﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace Webapi.Controllers
{
    public class UserController : Controller
    {
        //
        // GET: /User/

        public ActionResult Login()
        {
            //string pwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile("123456", "MD5");
            //return Content(pwd); 
            return View();
        }

        [HttpPost]
        public ActionResult Login(FormCollection obj)
        {
            string uname = ConfigHelper.GetValue("username");
            string pwd = ConfigHelper.GetValue("password");
            string enpwd = FormsAuthentication.HashPasswordForStoringInConfigFile(obj["upwd"].Trim(), "MD5");
            if (uname.Equals(obj["uname"].Trim(), StringComparison.CurrentCultureIgnoreCase) && pwd.Equals(enpwd))
            {
                var expire = DateTime.Now.Add(FormsAuthentication.Timeout);  //默认过期时间，30分钟

                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                                                           1,
                                                           uname,
                                                           DateTime.Now,
                                                           expire,
                                                           true,
                                                           "",
                                                           FormsAuthentication.FormsCookiePath
                                                       );

                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName);
                cookie.Domain = FormsAuthentication.CookieDomain;
                cookie.Path = FormsAuthentication.FormsCookiePath;
                cookie.Value = FormsAuthentication.Encrypt(ticket);
                cookie.Expires = expire;
                Response.Cookies.Add(cookie);

                return Redirect("/control/index");
            }
            else
            {
                ViewBag.Tips = "帐号密码错误！";
                return View();
            }
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("login");
        }
    }
}
